<template>
  <div class="sell-records-container">
    <!-- 顶部标题栏 -->
    <div class="header">

      <h1 class="title">卖出记录</h1>
      <button class="refresh-btn" @click="refreshData" :disabled="loading">
        <svg class="refresh-icon" :class="{ 'spinning': loading }" viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="M23 4v6h-6M1 20v-6h6M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4a9 9 0 0 1-14.85 4.36L23 14"/>
        </svg>
      </button>
    </div>

    <!-- 统计卡片 -->
    <div class="summary-card">
      <div class="summary-item">
        <span class="summary-label">卖出次数</span>
        <span class="summary-value">{{ totalTransactions }}笔</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">总收入</span>
        <span class="summary-value">{{ formatAmount(totalRevenue) }}</span>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="search-box">
        <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.35-4.35"/>
        </svg>
        <input
            type="text"
            placeholder="搜索股票代码..."
            v-model="searchKeyword"
            class="search-input"
        >
      </div>

      <div class="filter-row">
        <select v-model="sortBy" class="sort-select">
          <option value="sellDate">按日期排序</option>
          <option value="totalAmount">按收入排序</option>
          <option value="stockSymbol">按代码排序</option>
        </select>

        <button
            class="sort-order-btn"
            @click="toggleSortOrder"
            :title="sortOrder === 'desc' ? '降序' : '升序'"
        >
          <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path v-if="sortOrder === 'desc'" d="M3 6h18M7 12h10m-7 6h4"/>
            <path v-else d="M3 18h18M7 12h10m-7-6h4"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载中...</span>
    </div>

    <!-- 卖出记录列表 -->
    <div v-else-if="filteredRecords.length > 0" class="records-list">
      <div
          v-for="record in filteredRecords"
          :key="record.sellId"
          class="record-item"
          @click="showRecordDetail(record)"
      >
        <!-- 记录头部 -->
        <div class="record-header">
          <div class="stock-info">
            <span class="stock-symbol">{{ record.stockSymbol }}</span>
            <span class="sell-date">{{ formatDate(record.sellDate) }}</span>
          </div>
          <div class="record-id">#{{ record.sellId.toString().slice(-6) }}</div>
        </div>

        <!-- 交易详情 -->
        <div class="record-details">
          <div class="detail-group">
            <div class="detail-item">
              <span class="detail-label">卖出价格</span>
              <span class="detail-value">{{ formatPrice(record.sellPrice) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">卖出数量</span>
              <span class="detail-value">{{ record.quantity }}股</span>
            </div>
          </div>

          <div class="total-amount">
            <span class="amount-label">总收入</span>
            <span class="amount-value">{{ formatAmount(record.totalAmount) }}</span>
          </div>
        </div>

        <!-- 箭头指示器 -->
        <div class="arrow-indicator">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M9 18l6-6-6-6"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
        <polyline points="7,10 12,15 17,10"/>
        <line x1="12" y1="15" x2="12" y2="3"/>
      </svg>
      <p class="empty-text">{{ getEmptyText() }}</p>
    </div>


  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import {getUserSellStocky} from "@/api/user/userget";
import router from "@/router";
// 响应式数据
const records = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const sortBy = ref('sellDate')
const sortOrder = ref('desc')
const hasMore = ref(true)
const currentPage = ref(1)

// 计算属性
const filteredRecords = computed(() => {
  let filtered = records.value

  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter(record =>
        record.stockSymbol.toLowerCase().includes(keyword)
    )
  }

  // 排序
  filtered.sort((a, b) => {
    let aValue = a[sortBy.value]
    let bValue = b[sortBy.value]

    // 特殊处理日期排序
    if (sortBy.value === 'sellDate') {
      aValue = new Date(aValue)
      bValue = new Date(bValue)
    }

    if (sortOrder.value === 'desc') {
      return bValue > aValue ? 1 : -1
    } else {
      return aValue > bValue ? 1 : -1
    }
  })

  return filtered
})

const totalTransactions = computed(() => records.value.length)

const totalRevenue = computed(() => {
  return records.value.reduce((sum, record) => sum + record.totalAmount, 0)
})

// 方法
const fetchSellRecords = async (page = 1, reset = true) => {
  loading.value = true
  try {

    const {data}=await getUserSellStocky()

    const mockData = data

    if (reset) {
      records.value = mockData
      currentPage.value = 1
    } else {
      records.value = [...records.value, ...mockData]
      currentPage.value = page
    }

    // 模拟是否还有更多数据
    hasMore.value = page < 3



  } catch (error) {
    console.error('获取卖出记录失败:', error)
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  fetchSellRecords(1, true)
}



const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
}

const formatAmount = (amount) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(amount)
}

const formatPrice = (price) => {
  return `${price.toFixed(2)}`
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

const getEmptyText = () => {
  if (searchKeyword.value.trim()) {
    return '没有找到相关的卖出记录'
  }
  return '暂无卖出记录'
}

const showRecordDetail = (record) => {
  router.push({
    path: '/center/stockInformation',
    query: {
      stockSymbol: record.stockSymbol,
      stockNumber: record.stockNumber
    }
  })
}

import {useTokenStore} from "@/stores/token";
import toast from "@/utils/toast";
watch(searchKeyword, () => {
  // 可以添加防抖逻辑
})

// 生命周期
onMounted(() => {
  if(useTokenStore().hasToken){
   fetchSellRecords()
  }
  else {
    toast.warning("请先登录")
    router.push('/user/auth')
  }
})
</script>

<style scoped>
.sell-records-container {
  min-height: 100vh;
  background-color: #000;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding: 0 16px;
  padding-bottom: 80px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #333;
}

.back-btn, .refresh-btn {
  background: none;
  border: 1px solid #444;
  border-radius: 8px;
  padding: 8px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover, .refresh-btn:hover:not(:disabled) {
  border-color: #666;
  background-color: #111;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.back-icon, .refresh-icon {
  width: 20px;
  height: 20px;
}

.refresh-icon.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.summary-card {
  background-color: #111;
  border-radius: 12px;
  padding: 20px;
  margin: 20px 0;
  display: flex;
  justify-content: space-around;
}

.summary-item {
  text-align: center;
}

.summary-label {
  display: block;
  font-size: 14px;
  color: #999;
  margin-bottom: 8px;
}

.summary-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
}

.summary-value.profit {
  color: #4ade80;
}

.summary-value.loss {
  color: #f87171;
}

.filter-section {
  margin-bottom: 20px;
}

.search-box {
  position: relative;
  margin-bottom: 12px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  color: #666;
}

.search-input {
  width: 100%;
  background-color: #111;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 12px 12px 12px 40px;
  color: #fff;
  font-size: 16px;
  box-sizing: border-box;
}

.search-input:focus {
  outline: none;
  border-color: #666;
}

.search-input::placeholder {
  color: #666;
}

.filter-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.sort-select {
  flex: 1;
  background-color: #111;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 10px 12px;
  color: #fff;
  font-size: 14px;
}

.sort-select:focus {
  outline: none;
  border-color: #666;
}

.sort-order-btn {
  background-color: #111;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 10px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.sort-order-btn:hover {
  border-color: #666;
  background-color: #1a1a1a;
}

.sort-icon {
  width: 16px;
  height: 16px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #333;
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  color: #999;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  background-color: #111;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.record-item:hover {
  background-color: #1a1a1a;
}

.record-item:active {
  transform: scale(0.98);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.stock-info {
  display: flex;
  flex-direction: column;
}

.stock-symbol {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

.sell-date {
  font-size: 12px;
  color: #999;
}

.record-id {
  font-size: 12px;
  color: #666;
  background-color: #222;
  padding: 4px 8px;
  border-radius: 4px;
}

.record-details {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.detail-group {
  display: flex;
  gap: 24px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 14px;
  font-weight: 500;
}

.total-amount {
  display: flex;
  flex-direction: column;
  text-align: right;
}

.amount-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.amount-value {
  font-size: 16px;
  font-weight: 600;
  color: #4ade80;
}

.arrow-indicator {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.arrow-indicator svg {
  width: 16px;
  height: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  width: 64px;
  height: 64px;
  color: #333;
  margin-bottom: 16px;
}

.empty-text {
  color: #999;
  font-size: 16px;
  margin: 0;
}

.load-more-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.load-more-btn {
  background-color: #111;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 12px 24px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.load-more-btn:hover {
  border-color: #666;
  background-color: #1a1a1a;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .sell-records-container {
    padding: 0 12px;
  }

  .summary-card {
    margin: 16px 0;
    padding: 16px;
    flex-direction: column;
    gap: 16px;
  }

  .summary-item {
    display: flex;
    justify-content: space-between;
    text-align: left;
  }

  .record-item {
    padding: 14px;
  }

  .title {
    font-size: 20px;
  }

  .detail-group {
    gap: 16px;
    flex-wrap: wrap;
  }

  .record-details {
    flex-direction: column;
    gap: 12px;
  }

  .total-amount {
    text-align: left;
  }

  .filter-row {
    flex-direction: column;
    gap: 8px;
  }

  .sort-select {
    width: 100%;
  }
}
</style>